package com.wasu.sdk_ott.utils

import android.content.Context
import android.content.pm.PackageManager
import android.os.Environment
import android.util.Log
import com.wasu.UILApplication
import com.wasu.constant.Config
import com.wasu.livedata.library.BuildConfig
import com.wasu.rxcache.RxCache
import com.wasu.rxcache.diskconverter.GsonDiskConverter
import java.io.File

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> UILApplication初始化时调用
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/7/31
 */
object AppInitHelper {

    private const val TAG = "appLaunch"

    fun appInit(app: Context){
        RxCache.initializeDefault(createCache(app))
    }

    /**
     * 缓存配置
     * 缓存文件路径 /mnt/sdcard/Android/data/com.wasu.launcher/cache/ipLiveCache_01#4001
     * 无外置存储在 /data/user/0/com.wasu.launcher/cache/ipLiveCache_01#4001
     */
     private fun createCache(context: Context, version: Int? = 1): RxCache {
        return RxCache.Builder()
            .appVersion(version?: 1)
            .diskConverter(GsonDiskConverter())
            .memoryMax(10 * 1024 * 1024)
            .diskMax(100 * 1024 * 1024)
            .diskDir(getRxCachePath(context))
            .setDebug(BuildConfig.DEBUG)
            .build()
    }

    /**
     * 缓存文件路径 /storage/sdcard/Android/data/com.wasu.launcher/files/Documents/liveCache_IPEPG_01#4001
     */
    fun getRxCachePath(context: Context?): File {
        val childDir = "liveCache_${if (WasuTvModelUtil.isbIpMode()) "IPLIVE" else "IPEPG"}_${Config.getRegion()}"
        val cachePath = runCatching {
            if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() && hasExternalStoragePermission(context)){
                "${context?.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)?.absolutePath?: Environment.getDataDirectory()?.absolutePath}/$childDir"
            }else {
                "${context?.filesDir?.absolutePath?: Environment.getDataDirectory()?.absolutePath}/$childDir"
            }
        }.getOrDefault("/data/$childDir")
        Log.v(com.wasu.constant.TAG, "getRxCachePath, cachePath:$cachePath")
        return File(cachePath)
    }

    /**
     * 是否有写入权限
     */
    private fun hasExternalStoragePermission(context: Context? = UILApplication.getInstance().application.applicationContext): Boolean {
        return context?.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED
    }

}